package com.rp.system.user.controller;

import com.rp.common.aspect.annotetion.AutoLog;
import com.rp.common.aspect.annotetion.ResponseResultBody;
import com.rp.common.config.shiro.ShiroConfig;
import com.rp.common.result.ResultDTO;
import com.rp.common.utils.CreateRandom;
import com.rp.common.utils.Md5PassWordUtil;
import com.rp.common.utils.Selectway;
import com.rp.system.log.entity.SysLog;
import com.rp.system.log.service.SysLogService;
import com.rp.system.user.entity.SysUser;
import com.rp.system.user.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 类说明:
 *
 * @author ****
 * @date 2021-03-31 11:08  新建
 */
@Slf4j
@RestController
@RequestMapping("/apply")
@ResponseResultBody
@Api(tags = "应用管理")
public class ApplyController {

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private Selectway selectway;

    @AutoLog(value = "应用管理-应用ID")
    @ApiOperation(value = "应用ID")
    @RequestMapping(value = "/getClientId", method = RequestMethod.GET)
    public ResultDTO getClientId() {
        return ResultDTO.success().data(selectway.getSysUser().getClientId());
    }

    @AutoLog(value = "应用管理-重置秘钥")
    @ApiOperation(value = "重置秘钥")
    @RequestMapping(value = "/getSecret", method = RequestMethod.GET)
    public ResultDTO getSecret() {
        String secret = CreateRandom.createRandomCharData(24);
        SysUser sysUser = selectway.getSysUser();
        sysUserService.updateClientSecret(selectway.getUserName(),Md5PassWordUtil.getMd5(secret, sysUser.getUsername() + sysUser.getSalt(), ShiroConfig.HASH_ITERATIONS));
        return ResultDTO.success().data(secret);
    }

    @AutoLog(value = "应用管理-获取授权码TOKEN")
    @ApiOperation(value = "获取授权码TOKEN")
    @RequestMapping(value = "/getToken", method = RequestMethod.GET)
    public ResultDTO getToken(@RequestParam @ApiParam(value = "应用ID",required = true) String clientId,
                              @RequestParam @ApiParam(value = "应用秘钥",required = true) String clientSecret, HttpServletRequest request) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(clientId, clientSecret,true);
        Subject subject = SecurityUtils.getSubject();
        try {
            //登录操作
            subject.login(usernamePasswordToken);
            //保存日志
            String username = (String) SecurityUtils.getSubject().getPrincipal();
            SysUser user = sysUserService.showUser(username);
            sysLogService.save(new SysLog(1, "用户: " + user.getUsername() + ",应用授权成功！", user.getUsername(), user.getRealname(), request));
            Map<String,Object> map = new HashMap<>();
            map.put("tokenType", "rupeng");
            map.put("tokenValue", SecurityUtils.getSubject().getSession().getId());
            return ResultDTO.success().data(map).message("授权成功");
        } catch (UnknownAccountException uae) {
            return ResultDTO.USER_NOT_EXIST();
        } catch (LockedAccountException lae) {
            return ResultDTO.USER_ACCOUNT_FORBIDDEN();
        } catch (AuthenticationException ice) {
            return ResultDTO.bad().message("秘钥错误");
        }
    }

}
